package com.aquaestudio.ifadventures;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Main extends Activity implements Runnable {
	EditText command;
	EditText gametext;
	Button btnRefresh;
	Process game;
	BufferedReader in;
	BufferedWriter out;
	boolean bcontinue = true;

	@Override
	protected void onDestroy() {
		if (game != null)
			game.destroy();
		super.onDestroy();
	}

	private void refrescarSalida() {
		char a;

		try {
			while (in.ready() && (a = (char) in.read()) != -1) {
				gametext.append(String.valueOf(a));
			}
		} catch (IOException e) {
			Log.e("Salida", e.toString());
		}
	}

	private void Refrescar() {
		// refrescarSalida();
		String cad = command.getText().toString();

		if (cad.length() > 0) {
			cad = cad.trim() + "\n";

			try {
				out.write(cad);
				out.flush();
				gametext.append(cad);
				command.setText("");
				gametext.setSelection(gametext.getText().length());
			} catch (IOException e) {
				Log.e("Entrada", e.toString());
			}
		}
	}

	private boolean startGame() {

		try {
			game = new ProcessBuilder()
					.command("/data/data/com.aquaestudio.ifadventures/ifa",
							"/data/data/com.aquaestudio.ifadventures/tc2.ulx").redirectErrorStream(true).start();
			// in = game.getInputStream();
			// out = game.getOutputStream();
			in = new BufferedReader(new InputStreamReader(game.getInputStream()));
			out = new BufferedWriter(new OutputStreamWriter(game.getOutputStream()));
		} catch (IOException e) {
			Log.e("startGame", e.toString());
		}

		// Lanzamos una thread para leer ;-)
		Thread thread = new Thread(this);
		thread.start();

		/*
		 * Thread t = new Thread(new Runnable() { public void run() { while
		 * (bcontinue) refrescarSalida(); } }); t.start();
		 */

		return true;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gametext = (EditText) findViewById(R.id.gametext);
		startGame();
		
		command = (EditText) findViewById(R.id.command);
		command.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					Refrescar();
					return true;
				}
				return false;
			}
		});
		command.requestFocus();
	}

	@Override
	public void run() {
		char a;
		
		while (bcontinue) {
			try {
				while (in.ready() && (a = (char) in.read()) != -1) {
					Message m = new Message();
					Bundle b = new Bundle();
					b.putChar("datos", a);
					m.setData(b);
					handler.sendMessage(m);
				}
			} catch (IOException e) {
				Log.e("Salida", e.toString());
			}
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			gametext.append(String.valueOf(msg.getData().getChar("datos")));
			gametext.setSelection(gametext.getText().length());
		}
	};
}